package config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.script.Field;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 与SpringDataEsRepositoryConfig配置一样，但使用了spring提供的一些父配置类
 */
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.repository.dao")
@ComponentScan("com.repository")
public class SpringDataEsRepositoryConfig2 extends AbstractElasticsearchConfiguration {


    @Override
    public RestHighLevelClient elasticsearchClient() {
        return RestClients.create(ClientConfiguration.create("localhost:9200"))
                .rest();
    }

    //region 自定义转换器的编写与注册
    @Bean
    @Override
    public ElasticsearchCustomConversions elasticsearchCustomConversions() {
        return new ElasticsearchCustomConversions(
                Arrays.asList(new AddressToMap(), new MapToAddress()));
    }

    // Converter:org.springframework.core.convert.converter.Converter 别导错了类
    @WritingConverter
    static class AddressToMap implements Converter<Address, Map<String, Object>> {


        @Override
        public Map<String, Object> convert(Address source) {

            LinkedHashMap<String, Object> target = new LinkedHashMap<>();
            target.put("ciudad", source.getCity());
            // ...

            return target;
        }
    }

    @ReadingConverter
    static class MapToAddress implements Converter<Map<String, Object>, Address> {

        @Override
        public Address convert(Map<String, Object> source) {
            Address address = null;
            // ...
            return address;
        }
    }
    @Data
    static  class Address{
        private String city;
    }
    //endregion
}
